package com.ruitaowang.admin.view.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruitaowang.core.domain.*;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.CollectionService;
import com.ruitaowang.goods.service.CommentService;
import com.ruitaowang.goods.service.CompanyService;
import com.ruitaowang.goods.service.CouponService;
import com.ruitaowang.goods.service.DistrictService;
import com.ruitaowang.goods.service.GoodsAlbumService;
import com.ruitaowang.goods.service.GoodsAttributeLinkService;
import com.ruitaowang.goods.service.GoodsSearchService;
import com.ruitaowang.goods.service.GoodsService;
import com.ruitaowang.goods.service.GoodsTypeCustomService;
import com.ruitaowang.goods.service.HistoricalRecordService;
import com.ruitaowang.goods.service.OrderProdService;
import com.ruitaowang.goods.service.RebateRatioService;

/**
 * Created by neal on 11/17/16.
 */
@RestController
public class APIGoodsController extends BaseController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsSearchService goodsSearchService;
    @Autowired
    private GoodsAttributeLinkService goodsAttributeLinkService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private OrderProdService orderProdService;
    @Autowired
    private GoodsAlbumService goodsAlbumService;
    @Autowired
    private RebateRatioService rebateRatioService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private HistoricalRecordService historicalRecordService;
    @Autowired
    private DistrictService districtService;
    @Autowired
    private CollectionService collectionService;
    @Autowired
    private GoodsTypeCustomService goodsTypeCustomService;

    /**
     * @api {get} /api/goods 后台管理-商品管理-商品列表
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/goods
     * @apiName findGoodsPage
     * @apiGroup Goods
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "categoryId": 15,
     * "ctime": 1584201950317,
     * "goodsDetail": "<p><img src=\"http://static.ruitaowang.com/attached/file/20170612/20170612174837_22.jpg\" title=\"\" alt=\"快转.jpg\"/></p>",
     * "goodsDumySales": 764,
     * "goodsExPrice": 0,
     * "goodsId": 1592,
     * "goodsName": "快转-微传媒",
     * "goodsOnline": 1,
     * "goodsPayType": 0,
     * "goodsProviderId": 1,
     * "goodsProviderType": 127,
     * "goodsRealPrice": 0,
     * "goodsRecommendSort": 100,
     * "goodsScore": 0,
     * "goodsScreenPrice": 20000,
     * "goodsSn": "RT0000001592",
     * "goodsStock": 0,
     * "goodsThum": "http://static.ruitaowang.com/attached/file/20170508/20170508150742_129.jpg",
     * "mtime": 1493776561382,
     * "rstatus": 0,
     * "selfSupport": false
     * }
     * ],
     * "msg":"操作成功啦",
     * "records":5,
     * "title":"成功",
     * "total":1,
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/goods"
     * }
     */
    @RequestMapping(value = "/api/goods", method = RequestMethod.GET)
    public String findGoodsPage(Goods goods, int page) {
        goods.setPage(page);
        if (!ObjectUtils.isEmpty(goods.getSidx())) {
            goods.setOrderBy(goods.getSidx() + " " + goods.getSord() + "," + goods.getOrderBy());
        }
        MsgOut o = MsgOut.success(goodsService.goodsSearch(goods));
        o.setRecords(goods.getRecords());
        o.setTotal(goods.getTotal());
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/warning/goods", method = RequestMethod.GET)
    public String selectForWarningPage(Goods goods, int page) {
        goods.setPage(page);
        if (!ObjectUtils.isEmpty(goods.getSidx())) {
            goods.setOrderBy(goods.getSidx() + " " + goods.getSord() + "," + goods.getOrderBy());
        }
        MsgOut o = MsgOut.success(goodsService.selectForWarning(goods));
        o.setRecords(goods.getRecords());
        o.setTotal(goods.getTotal());
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/admin/goods", method = RequestMethod.GET)
    public String adminGoods(Goods goods,int page) {
        goods.setPage(page);
        if (!ObjectUtils.isEmpty(goods.getSidx())) {
            goods.setOrderBy(goods.getSidx() + " " + goods.getSord() + "," + goods.getOrderBy());
        }
        MsgOut o = MsgOut.success(goodsService.goodsAdminSearch(goods));
        o.setRecords(goods.getRecords());
        o.setTotal(goods.getTotal());
        return this.renderJson(o);
    }

    /**
     * 龙蛙商城-商城系统列表
     *
     * @return
     */
    @RequestMapping(value = "/api/goods/ruitao", method = RequestMethod.GET)
    public String findGoodsForRT() {
        // 2473 1592 1843 1844 1845
        long[] goods = {2473, 1592, 1843, 1831, 1844, 1845, 2692};
        List<Goods> goodses = new ArrayList<>(goods.length);
        for (int i = 0; i < goods.length; i++) {
            goodses.add(goodsService.selectByPK(goods[i]));
        }

        return this.renderJson(MsgOut.success(goodses));
    }

    /**
     * @api {get} /api/ws/goods 后台管理-微商-商品管理-商品列表
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/ws/goods
     * @apiName findGoodsPageWs
     * @apiGroup Goods
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "categoryId": 15,
     * "ctime": 1584201950317,
     * "goodsDetail": "<p><img src=\"http://static.ruitaowang.com/attached/file/20170612/20170612174837_22.jpg\" title=\"\" alt=\"快转.jpg\"/></p>",
     * "goodsDumySales": 764,
     * "goodsExPrice": 0,
     * "goodsId": 1592,
     * "goodsName": "快转-微传媒",
     * "goodsOnline": 1,
     * "goodsPayType": 0,
     * "goodsProviderId": 1,
     * "goodsProviderType": 127,
     * "goodsRealPrice": 0,
     * "goodsRecommendSort": 100,
     * "goodsScore": 0,
     * "goodsScreenPrice": 20000,
     * "goodsSn": "RT0000001592",
     * "goodsStock": 0,
     * "goodsThum": "http://static.ruitaowang.com/attached/file/20170508/20170508150742_129.jpg",
     * "mtime": 1493776561382,
     * "rstatus": 0,
     * "selfSupport": false
     * }
     * ],
     * "msg":"操作成功啦",
     * "records":5,
     * "title":"成功",
     * "total":1,
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/ws/goods"
     * }
     */
    @RequestMapping(value = "/api/ws/goods", method = RequestMethod.GET)
    public String findGoodsPageWs(Goods goods, int page) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }

        Company company = companyService.selectByUserId(user.getId());
        goods.setPage(page);
        goods.setGoodsProviderId(company.getCompanyId());
        if (!ObjectUtils.isEmpty(goods.getSidx())) {
            goods.setOrderBy(goods.getSidx() + " " + goods.getSord() + "," + goods.getOrderBy());
        }
        MsgOut o = MsgOut.success(goodsSearchService.searchForPage(goods));
        o.setRecords(goods.getRecords());
        o.setTotal(goods.getTotal());
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/goods/:goodsId 后台管理-微商-商品管理-商品列表ByPK
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/goods/:goodsId
     * @apiName findGoodsByPK
     * @apiGroup Goods
     * @apiParam {int} goodsId 商品ID.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "categoryId": 15,
     * "ctime": 1584201950317,
     * "goodsDetail": "<p><img src=\"http://static.ruitaowang.com/attached/file/20170612/20170612174837_22.jpg\" title=\"\" alt=\"快转.jpg\"/></p>",
     * "goodsDumySales": 764,
     * "goodsExPrice": 0,
     * "goodsId": 1592,
     * "goodsName": "快转-微传媒",
     * "goodsOnline": 1,
     * "goodsPayType": 0,
     * "goodsProviderId": 1,
     * "goodsProviderType": 127,
     * "goodsRealPrice": 0,
     * "goodsRecommendSort": 100,
     * "goodsScore": 0,
     * "goodsScreenPrice": 20000,
     * "goodsSn": "RT0000001592",
     * "goodsStock": 0,
     * "goodsThum": "http://static.ruitaowang.com/attached/file/20170508/20170508150742_129.jpg",
     * "mtime": 1493776561382,
     * "rstatus": 0,
     * "selfSupport": false
     * }
     * ],
     * "msg":"操作成功啦",
     * "records":5,
     * "title":"成功",
     * "total":1,
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/goods/{goodsId}"
     * }
     */

    @RequestMapping(value = "/api/goods/{goodsId}", method = RequestMethod.GET)
    public String findGoodsByPK(@PathVariable("goodsId") Long goodsId) {
        MsgOut o = MsgOut.success(goodsService.selectByPK(goodsId));
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/wap/goods/order/{goodsId}", method = RequestMethod.GET)
    public String findWapGoodsByPK(@PathVariable("goodsId") Long goodsId) {
        if (ObjectUtils.isEmpty(goodsId)){
            return this.renderJson(MsgOut.error("参数错误"));
        }
        Goods goods=goodsService.selectByPK(goodsId);
        if (ObjectUtils.isEmpty(goods)){
            return this.renderJson(MsgOut.error("查询不到商品信息"));
        }
        List<GoodsVO> goodsVOS = new ArrayList<>();
        CompanyVO companyVO = new CompanyVO();
        GoodsVO goodsVO = new GoodsVO();
        Company company=companyService.selectByPK(1L);
        BeanUtils.copyProperties(company,companyVO);
        BeanUtils.copyProperties(goods,goodsVO);
        goodsVOS.add(goodsVO);
        companyVO.setGoodsList(goodsVOS);
        MsgOut o = MsgOut.success(companyVO);
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/goods/albums/{goodsId}", method = RequestMethod.GET)
    public String findGoodsAlbum(@PathVariable("goodsId") Long goodsId) {
        GoodsAlbum goodsAlbum = new GoodsAlbum();
        goodsAlbum.setGoodsId(goodsId);
        goodsAlbum.setImageType((byte) 1);
        return this.renderJson(goodsService.selectAlbum(goodsAlbum));
    }

    @RequestMapping(value = "/goods/update/setUpWarning", method = RequestMethod.GET)
    public String setUpWarning(int val) {
               goodsService.setUpWarning(val);
        return this.renderJson(MsgOut.success(val));
    }
    /**
     * 获取商品详情图片
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/api/goods/detailsAlbums/{goodsId}", method = RequestMethod.GET)
    public String findGoodsDetailsAlbum(@PathVariable("goodsId") Long goodsId) {
        GoodsAlbum goodsAlbum = new GoodsAlbum();
        goodsAlbum.setGoodsId(goodsId);
        goodsAlbum.setImageType((byte) 2);
        return this.renderJson(goodsService.selectAlbum(goodsAlbum));
    }



    /**
     * @api {post} /api/goods 后台管理-微商-商品管理-添加商品
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/goods
     * @apiPermission admin
     * @apiName createGoods
     * @apiGroup Goods
     * @apiParam {long} categoryId 商品货号.
     * @apiParam {long} goodsProviderId 供货商ID.
     * @apiParam {int} goodsScreenPrice 本店价格.
     * @apiParam {int} goodsRealPrice 进货价格.
     * @apiParam {Byte} goodsPayType 支付类型.
     * @apiParam {int} goodsExPrice 商品运费.
     * @apiParam {long} goodsBrandId 品牌ID.
     * @apiParam {int} goodsWeight 商品重量.
     * @apiParam {int} goodsScore 商品积分.
     * @apiParam {Byte} goodsGetType 提货方式.
     * @apiParam {string} goodsSN 商品货号.
     * @apiParam {string} goodsName 商品名称.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":
     * {
     * "categoryId": 18,
     * "ctime": 1504680819954,
     * "goodsExPrice": 11,
     * "goodsGetType": 1,
     * "goodsId": 2443,
     * "goodsName": "11111",
     * "goodsPayType": 1,
     * "goodsProviderId": 274,
     * "goodsProviderType": 1,
     * "goodsRealPrice": 11,
     * "goodsScore": 1,
     * "goodsScreenPrice": 1111,
     * "goodsSn": "RT000000null",
     * "goodsWeight": 11,
     * "mtime": 1504680819954
     * },
     * "msg":"操作成功啦",
     * "records":5,
     * "title":"成功",
     * "total":1,
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/goods"
     * }
     */
    @RequestMapping(value = "/api/goods", method = RequestMethod.POST)
    public String createGoods(Goods goods,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(goods.getGoodsSn())) {
            goods.setGoodsSn(generateSN(goods.getGoodsId()));
        }
        if (goods.getGoodsScreenPrice() == 0) {
            return this.renderJson(MsgOut.error("价格设置不能为0元"));
        }
        //供货商类型 0 实体店，1 微商， 8 供货商 127 龙蛙自己的产品
        Company company = companyService.selectByPK(1L);
        if (!ObjectUtils.isEmpty(company)) {
            goods.setCategoryId(company.getCompanyTypeId());
        }
        if (!ObjectUtils.isEmpty(company)) {
            goods.setGoodsProviderType(company.getCompanyType());
            goods.setGoodsProviderId(company.getCompanyId());
        }
        if (!ObjectUtils.isEmpty(goods.getGoodsScore())) {
            goods.setGoodsScore(goods.getGoodsScore() * 100);
        }
        goods.setGoodsOnline((byte)2);
        goods = goodsService.insert(goods);
        MsgOut o = MsgOut.success(goods);
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/admin/goods", method = RequestMethod.POST)
    public String adminCreateGoods(Goods goods) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
//        if (ObjectUtils.isEmpty(goods.getGoodsSn())) {
//            goods.setGoodsSn(generateSN(goods.getGoodsId()));
//        }
        //供货商类型 0 实体店，1 微商， 8 供货商 127 龙蛙自己的产品
        Company company = companyService.selectByPK(1L);
//        if (!ObjectUtils.isEmpty(company)) {
//            goods.setCategoryId(company.getCompanyTypeId());
//        }
        if (!ObjectUtils.isEmpty(company)) {
            goods.setGoodsProviderType(company.getCompanyType());
            goods.setGoodsProviderId(company.getCompanyId());
        }

        if (!ObjectUtils.isEmpty(goods.getGoodsScreenPrice())) {
            goods.setGoodsScreenPrice(goods.getGoodsScreenPrice() * 100);
        }
        if (!ObjectUtils.isEmpty(goods.getGoodsRealPrice())) {
            goods.setGoodsRealPrice(goods.getGoodsRealPrice() * 100);
        }
        if (!ObjectUtils.isEmpty(goods.getGoodsExPrice())) {
            goods.setGoodsExPrice(goods.getGoodsExPrice() * 100);
        }
        if (!ObjectUtils.isEmpty(goods.getGoodsScore())) {
            goods.setGoodsScore(goods.getGoodsScore() * 100);
        }
        goods = goodsService.insert(goods);
        goods.setGoodsSn(String.format("%05d",goods.getGoodsId()));
        goodsService.update(goods);
        MsgOut o = MsgOut.success(goods);
        return this.renderJson(o);
    }

    /**
     * 新增后台管理商品详情图
     * @param goodsAlbum
     * @param imgUrl
     * @param detailePictureUrl
     * @return
     */
    @RequestMapping(value = "/api/admin/goodsAlbum/create", method = RequestMethod.POST)
    public String createGoodsAlbum(GoodsAlbum goodsAlbum, String imgUrl, String detailePictureUrl) {
        if (!ObjectUtils.isEmpty(imgUrl)) {
            String url[] = imgUrl.split(",");
            goodsAlbum.setImageType((byte)1);
            for (int i = 0; i < url.length; i++) {
                goodsAlbum.setUrl(url[i]);
                goodsAlbumService.insert(goodsAlbum);
            }
        }
        if (!ObjectUtils.isEmpty(detailePictureUrl)) {
            String detailesUrl[] = detailePictureUrl.split(",");
            goodsAlbum.setImageType((byte)2);
            for (int i = 0; i < detailesUrl.length; i++) {
                goodsAlbum.setUrl(detailesUrl[i]);
                goodsAlbumService.insert(goodsAlbum);
            }
        }
        MsgOut o = MsgOut.success(goodsAlbum);
        return this.renderJson(o);
    }

    /**
     * 更新后台管理商品详情图
     * @param goodsId
     * @param imgUrl
     * @param detailePictureUrl
     * @return
     */
    @RequestMapping(value = "/api/admin/goodsAlbum/update", method = RequestMethod.PUT)
    public String updateGoodsAlbum(Long goodsId, String imgUrl, String detailePictureUrl) {
        if (!ObjectUtils.isEmpty(imgUrl)) {
            GoodsAlbum goodsAlbum = new GoodsAlbum();
            goodsAlbum.setGoodsId(goodsId);
            goodsAlbum.setImageType((byte)1);
            List<GoodsAlbum> goodsAlbumList = goodsAlbumService.select(goodsAlbum);
            if (!ObjectUtils.isEmpty(goodsId)) {
                for (GoodsAlbum where : goodsAlbumList) {
                    goodsAlbumService.delete(where.getImageId());
                }
            }
            String url[] = imgUrl.split(",");
            for (int i = 0; i < url.length; i++) {
                goodsAlbum.setUrl(url[i]);
                goodsAlbumService.insert(goodsAlbum);
            }
        }
        if (!ObjectUtils.isEmpty(detailePictureUrl)) {
            GoodsAlbum goodsAlbum = new GoodsAlbum();
            goodsAlbum.setGoodsId(goodsId);
            goodsAlbum.setImageType((byte)2);
            List<GoodsAlbum> goodsAlbumList = goodsAlbumService.select(goodsAlbum);
            if (!ObjectUtils.isEmpty(goodsId)) {
                for (GoodsAlbum where : goodsAlbumList) {
                    goodsAlbumService.delete(where.getImageId());
                }
            }
            String detailesUrl[] = detailePictureUrl.split(",");
            for (int i = 0; i < detailesUrl.length; i++) {
                goodsAlbum.setUrl(detailesUrl[i]);
                goodsAlbumService.insert(goodsAlbum);
            }
        }
        MsgOut o = MsgOut.success("操作成功了！");
        return this.renderJson(o);
    }


    /**
     * @api {post} /api/goods/cellEdit 后台管理-商品管理-商品列表-[上架下架CellEdit]
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/goods/cellEdit
     * @apiPermission admin
     * @apiName updateGoodsForCellEdit
     * @apiGroup Order
     * @apiParam {int} id 商品ID[必选].
     * @apiParam {byte} goodsOnline 上架下架[必选].
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "goodsOnline": 1,
     * "id": 363,
     * }
     * ],
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/goods/cellEdit"
     * }
     */

    @RequestMapping(value = "/api/goods/cellEdit", method = RequestMethod.POST)
    public String updateGoodsForCellEdit(Goods goods, long id) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        goods.setGoodsId(id);
        goodsService.update(goods);
        MsgOut o = MsgOut.success(goods);
        return this.renderJson(o);
    }

    /**
     * @api {post} /api/goods 后台管理-微商-商品管理-商品列表-修改商品
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/goods
     * @apiPermission admin
     * @apiName updateGoods
     * @apiGroup Goods
     * @apiParam {long} categoryId 商品货号.
     * @apiParam {long} goodsProviderId 供货商ID.
     * @apiParam {int} goodsScreenPrice 本店价格.
     * @apiParam {int} goodsRealPrice 进货价格.
     * @apiParam {Byte} goodsPayType 支付类型.
     * @apiParam {int} goodsExPrice 商品运费.
     * @apiParam {long} goodsBrandId 品牌ID.
     * @apiParam {int} goodsWeight 商品重量.
     * @apiParam {int} goodsScore 商品积分.
     * @apiParam {Byte} goodsGetType 提货方式.
     * @apiParam {string} goodsSN 商品货号.
     * @apiParam {string} goodsName 商品名称.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":
     * {
     * "categoryId": 18,
     * "ctime": 1504680819954,
     * "goodsExPrice": 11,
     * "goodsGetType": 1,
     * "goodsId": 2443,
     * "goodsName": "11111",
     * "goodsPayType": 1,
     * "goodsProviderId": 274,
     * "goodsProviderType": 1,
     * "goodsRealPrice": 11,
     * "goodsScore": 1,
     * "goodsScreenPrice": 1111,
     * "goodsSn": "RT000000null",
     * "goodsWeight": 11,
     * "mtime": 1504680819954
     * },
     * "msg":"操作成功啦",
     * "records":5,
     * "title":"成功",
     * "total":1,
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/goods"
     * }
     */
    @RequestMapping(value = "/api/goods", method = RequestMethod.PUT)
    public String updateGoods(Goods goods) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        List<OrderProd> orderProds = new ArrayList<OrderProd>();
        List ware = new ArrayList();
        //供货商类型 0 实体店，1 微商， 8 供货商 127 龙蛙自己的产品
        Company company = companyService.selectByPK(goods.getGoodsProviderId());
        if (!ObjectUtils.isEmpty(company)) {
            goods.setGoodsProviderType(company.getCompanyType());
            goods.setGoodsProviderId(company.getCompanyId());
        }
        goodsService.update(goods);
        if (!ObjectUtils.isEmpty(goods.getGoodsProviderId())) {
            OrderProd orderProd = new OrderProd();
            orderProd.setGoodsId(goods.getGoodsId());
            orderProds = orderProdService.select(orderProd);
            for (OrderProd op : orderProds) {
                orderProd.setProdId(op.getProdId());
                orderProd.setGoodsProviderId(goods.getGoodsProviderId());
                orderProd.setGoodsProviderType(goods.getGoodsProviderType());

                orderProdService.update(orderProd);
                ware.add(op.getOrderId());
                ware.add(orderProd.getGoodsId());
                ware.add(orderProd.getGoodsProviderId());
            }
        }
        ware.add(goodsService.selectByPK(goods.getGoodsId()));
        MsgOut o = MsgOut.success(ware);
        return this.renderJson(o);
    }



    /**
     * @api {delete} /api/goods/:goodsId 删除活动
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/goods/:goodsId
     * @apiPermission admin
     * @apiName deleteGoods
     * @apiGroup Goods
     * @apiParam {long} goodsId 商品ID.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":1,
     * "msg":"操作成功啦",
     * "records":5,
     * "title":"成功",
     * "total":1,
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/goods/{goodsId}"
     * }
     */
    @RequestMapping(value = "/api/goods/{goodsId}", method = RequestMethod.DELETE)
    public String deleteGoods(@PathVariable("goodsId") Long goodsId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        MsgOut o = MsgOut.success(goodsService.delete(goodsId));
        return this.renderJson(o);
    }


    @RequestMapping(value = "/api/goods/attributes/{goodsAttrLinkId}")
    public String getGoodsAttributes(@PathVariable String goodsAttrLinkId) {

        MsgOut o = MsgOut.success(goodsAttributeLinkService.getGoodsAttributeForString(goodsAttrLinkId));
        return this.renderJson(o);
    }

    /**
     * @api {DELETE} /api/goods/album/:imageId 公众号-删除产品图片
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/goods/album/:imageId
     * @apiName deleteAlbum
     * @apiGroup Goods
     * @apiParam {Long} imageId 商品图片Id.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     */
    @RequestMapping(value = "/api/goods/album/{imageId}", method = RequestMethod.DELETE)
    public String deleteAlbum(@PathVariable("imageId") Long imageId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }

        MsgOut o = MsgOut.success(goodsService.deleteAlbum(imageId));
        return this.renderJson(o);
    }

    private String generateSN(Long goodsId) {
        StringBuffer sb = new StringBuffer();
        sb.append(goodsId);
        int zeroLen = 10 - sb.length();
        for (int i = 0; i < zeroLen; i++) {
            sb.insert(0, 0);
        }
        sb.insert(0, "RT");
        return sb.toString();
    }

    @RequestMapping(value = "/api/admin/express")
    public String EXhTTP(String url) {
        //get请求返回结果
        JSONObject jsonResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.parseObject(strResult);
            } else {
            }
        } catch (IOException e) {

        }
        MsgOut o = MsgOut.success(jsonResult);
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/goods/goodsCount 公众号-商品个数
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/goods/goodsCount
     * @apiName goodsCount
     * @apiGroup Goods
     * @apiParam {Long} goodsId 商品Id.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     */
    @RequestMapping(value = "/api/goods/goodsCount", method = RequestMethod.GET)
    public String goodsCount(Goods goods) {
        Map map = new HashMap();
        if (!ObjectUtils.isEmpty(goods.getSidx())) {
            goods.setOrderBy(goods.getSidx() + " " + goods.getSord() + "," + goods.getOrderBy());
        }
        Long goodsCount = goodsService.goodscount(goods);
        map.put("goodsCount",goodsCount);
        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/admin/fjGoods", method = RequestMethod.POST)
    public String fjCreateGoods(Long goodsId,Long companyId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Goods goods = goodsService.selectByPK(goodsId);
        Company company = companyService.selectByPK(companyId);
        if (!ObjectUtils.isEmpty(company)) {
            goods.setGoodsProviderType(company.getCompanyType());
            goods.setGoodsProviderId(companyId);
        }
        goods = goodsService.insert(goods);
        goods.setGoodsSn(generateSN(goods.getGoodsId()));
        goodsService.update(goods);
        MsgOut o = MsgOut.success(goods);
        return this.renderJson(o);
    }

}
